#include "fileTransfer.h"

int download(int sockfd, const char *filename)
{
    train_t train;

    // 发送要下载的文件名
    train.length = strlen(filename);
    strncpy(train.data, filename, train.length);
    train.data[train.length + 1] = '\0';
    send(sockfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

    // 文件下载完成度百分比
    off_t filesize;
    recv(sockfd, &train.length, sizeof(train.length), MSG_WAITALL);
    recv(sockfd, &train.data, train.length, MSG_WAITALL);
    memcpy(&filesize, train.data, train.length);
    printf("filesize = %ld\n", filesize);

    off_t cur_size = 0;             // 已接收的文件数据量
    off_t last_size = 0;            // 上次打印的cur_size
    off_t slice = filesize / 10000; // 分片

    // 创建文件并接收数据
    int fd = open(train.data, O_RDWR | O_CREAT | O_TRUNC, 0666); // 创建文件

    while (1)
    {
        recv(sockfd, &train.length, sizeof(train.length), MSG_WAITALL); // 数据长度 - 接收对方的火车头 4B
        if (train.length == 0)
        {
            break;
        }
        recv(sockfd, &train.data, train.length, MSG_WAITALL); // 数据内容
        write(fd, train.data, train.length);                  // 将接收到的数据写入fd文件描述符指向的文件

        // 打印进度条
        cur_size += train.length;
        if (cur_size - last_size > slice)
        {
            printf("download %lf%%\r", 100.0 * cur_size / filesize);
            fflush(stdout);
            last_size = cur_size;
        }
    }

    printf("download 100%%\n");

    close(fd);
    return 0;
}
